#include"queue.h"

void QueueInit(Queue* pq)
{
    assert(pq);
    pq->head = pq->tail = NULL;
}
void QueueDestory(Queue* pq)
{
    assert(pq);
    QNode* cur = pq->head;
    while(cur)
    {
        QNode* next = cur->next;
        free(cur);
        cur = next;
    }
    pq->head = pq->tail = NULL;
}
void QueuePush(Queue* pq, QDataType x)
{
    assert(pq);
    //申请节点
    QNode* newnode = (QNode*)malloc(sizeof(QNode));
    if(newnode == NULL)
    {
        perror("malloc fail");
        exit(-1);
    }
    newnode->data = x;
    newnode->next = NULL;
    //插入
    if(pq->head == NULL)
    {
        pq->head = newnode;
        pq->tail = newnode;
    }
    else{
        pq->tail->next = newnode;
        pq->tail = newnode;
    }
}
void QueuePop(Queue* pq)
{
    assert(pq);
    assert(!QueueEmpty(pq));
    if(pq->head->next == NULL)
    {
        free(pq->head);
        pq->head = pq->tail = NULL;
    }
    else
    {
        QNode* next = pq->head->next;
        free(pq->head);
        pq->head = next;
    }
   
}
QDataType QueueBack(Queue* pq) {assert(pq); assert(!QueueEmpty(pq));return pq->tail->data;}
QDataType QueueFront(Queue* pq) {assert(pq); assert(!QueueEmpty(pq));return pq->head->data;} 
int QueueSize(Queue* pq)
{
    assert(pq);
    int size = 0;
    QNode* cur = pq->head;
    while(cur != NULL)
    {
        size++;
        cur =cur->next;
    }
    return size;
}
bool QueueEmpty(Queue* pq)
{
    assert(pq);
    return (pq->head == NULL) && (pq->tail == NULL);
}
